<?php

namespace app\common\logic;

use think\Model;

class Config extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 根据名称获取配置值
     * @param $name
     * @return array
     * @author wb <pithyone@vip.qq.com>
     */
    public static function val($name)
    {
        $cache_name = 'cache_name_' . $name;
        $value = self::where(['name' => $name])->cache($cache_name)->value('value', "");
        $ret = self::parse($value);

        return $ret;
    }

    /**
     * 解析数据
     * @param $data
     * @return array|mixed
     */
    private static function parse($data)
    {
        //过滤mysql连接、URL链接
        if (is_string($data)) {
            if (strpos($data, 'mysql:') === 0 || strpos($data, 'http:') === 0 || strpos($data, 'https:') === 0)
                return $data;
        }

        $ret = [];

        $ret_preg = preg_split('/[,;\r\n]+/', trim($data, ",;\r\n"));

        if (strpos($data, ':')) {
            foreach ($ret_preg as $key => $val) {
                list($k, $v) = explode(':', $val);
                $ret[$key]['id'] = $k;
                $ret[$key]['name'] = $v;
            }
        } else {
            if (is_array($ret_preg) && count($ret_preg) == 1)
                return $ret_preg[0];

            $ret = $ret_preg;
        }

        return $ret;
    }
}